#include "Encrypter.h"
#include "string.h"

Encrypter::Encrypter(const char* keyName)
{
  // read carrier's public key into rsaPub
	BIO* rsaPublicBio2 = BIO_new_file(keyName, "r");
	rsaPub = RSA_new();
	PEM_read_bio_RSAPublicKey(rsaPublicBio2, &rsaPub, NULL, NULL);
	BIO_free(rsaPublicBio2);

  modulusSize = RSA_size(rsaPub);
  workingBuffer = new unsigned char[modulusSize];
}

Encrypter::~Encrypter()
{
	RSA_free(rsaPub);
  delete workingBuffer;
}

char* Encrypter::EncryptData(const char* inBuf, int len, int* encryptedLen)
{
  //XXX need to handle larger lens than modulusSize
  unsigned char* encrypt_buf = new unsigned char[modulusSize];

	memset((void*) workingBuffer, 0, modulusSize);
	memset((void*) encrypt_buf, 0, modulusSize);
  memcpy(workingBuffer, inBuf, len);

  *encryptedLen = RSA_public_encrypt(len + 1,
			workingBuffer, (unsigned char*)encrypt_buf, rsaPub, PADDING);

  return ((char*)encrypt_buf);
}
